package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.pojo.SoundTimeLine;
import com.tanhua.dubbo.server.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class PeachBlossomImpl implements PeachBlossomApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;
    @Autowired
    private UserLikeApi userLikeApi;
    @Override
    public String sendSound(Sound sound) {
        try {
            //校验
            if(!ObjectUtil.isAllNotEmpty(sound.getUserId(), sound.getSoundUrl())){
                return null;
            }
            if(querySoundCountByOneDay(sound.getUserId().toString()) == null){
                return null;
            }
            //设置id
            sound.setId(ObjectId.get());
            sound.setSid(this.idService.createId(IdType.SOUND));

            //发布时间
            sound.setCreated(System.currentTimeMillis());

            //保存到Mongodb中
            this.mongoTemplate.save(sound);

            return sound.getId().toHexString();
        } catch (Exception e) {
            log.error("发送语音失败~ soundId = " + sound.getUserId(),e);
        }
        return null;
    }

    @Override
    public List<Sound> querySoundByUser(String userId) {
        return this.mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Sound.class);
    }

    @Override
    public Long querySoundCountByOneDay(String userId) {
        try {
            Query query = getQuery(Convert.toInt(userId));
            Long count = this.mongoTemplate.count(query, Sound.class);
            if(count > 8)
            {
                return null;
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Query getQuery(Integer userId) {
        if (!ObjectUtil.isNotEmpty(userId)) {
            return null;
        }
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId)
                .andOperator(Criteria.where("created").gte(minDate),
                        Criteria.where("created").lte(maxDate)
                )
        );
        return query;
    }

    @Override
    public Long queryUserListenerCount(String userId) {
        try {
            Query query = getQuery(Convert.toInt(userId));
            Long count = this.mongoTemplate.count(query, SoundTimeLine.class);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Sound querySoundRandom(Long userId) {
        try {
            //排除已喜欢或不喜欢的用户
            List<Long> userIds = new ArrayList<>();
            //查询喜欢列表
            userIds.addAll(this.userLikeApi.queryLikeList(userId));

            //查询不喜欢列表
            userIds.addAll(this.userLikeApi.queryNotLikeList(userId));

            //构造查询条件
            Criteria criteria = null;
            if(CollUtil.isNotEmpty(userIds)){
                //加入到查询条件中，排除这些用户
                criteria = Criteria.where("userId").nin(userIds);
            }
            Query query = Query.query(criteria);
            Long count = this.mongoTemplate.count(query, Sound.class);
            int startNum = RandomUtil.randomInt(0,count.intValue());
            query.skip(startNum).limit(1);
            List<Sound> soundList = this.mongoTemplate.find(query, Sound.class);
            SoundTimeLine soundTimeLine = new SoundTimeLine(ObjectId.get(),soundList.get(0).getSid(),userId,System.currentTimeMillis());
            if(queryUserListenerCount(userId.toString()) < 8){
                mongoTemplate.save(soundTimeLine);
            }
            return soundList.get(0);
        } catch (Exception e) {
            log.error("查询失败~ soundId = " + userId, e);
        }
        return null;
    }
}
